<?php
declare (strict_types = 1);

namespace app\middleware;
use thans\jwt\exception\JWTException;
use thans\jwt\exception\TokenBlacklistException;
use thans\jwt\exception\TokenExpiredException;
use thans\jwt\exception\TokenInvalidException;
use thans\jwt\facade\JWTAuth;
use think\facade\Log;
use think\Exception;
class CheckToken
{
    /**
     * 验证token
     * 将token加入header，如下：Authorization:bearer token值
     */
    public function handle($request, \Closure $next)
    {

        try {

            $payload = JWTAuth::auth();
            Log::record($payload);
            Log::record(JWTAuth::token()->get());

            $request->member_id = $payload['member_id']->getValue();
        }catch (TokenInvalidException $e){
            return abort(0,'token非法');
        }catch (TokenExpiredException $e){
            return abort(0,'token过期');
        }catch (TokenBlacklistException $e){
            return abort(0,'请重新获取登录凭据');
        }catch (JWTException  $e) {
            //$e->getCode(),$e->getMessage()
            return abort(json(['code'=>0,'msg'=>$e->getMessage()]));
        }
        return $next($request);
    }


}
